package com.xmg.p2p.business.service.impl;

import com.xmg.p2p.base.domain.Account;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.query.PageResult;
import com.xmg.p2p.base.service.IAccountService;
import com.xmg.p2p.base.service.IUserinfoService;
import com.xmg.p2p.base.util.BidConst;
import com.xmg.p2p.base.util.BitStatesUtils;
import com.xmg.p2p.base.util.UserContext;
import com.xmg.p2p.business.domain.MoneyWithdraw;
import com.xmg.p2p.business.domain.UserBankinfo;
import com.xmg.p2p.business.mapper.MoneyWithdrawMapper;
import com.xmg.p2p.business.query.MoneyWithdrawQueryObject;
import com.xmg.p2p.business.service.IAccountFlowService;
import com.xmg.p2p.business.service.IMoneyWithdrawService;
import com.xmg.p2p.business.service.ISystemAccountService;
import com.xmg.p2p.business.service.IUserBankinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class MoneyWithdrawServiceImpl implements IMoneyWithdrawService {

    @Autowired
    private MoneyWithdrawMapper moneyWithdrawMapper;

    @Autowired
    private IUserinfoService userinfoService;

    @Autowired
    private IAccountService accountService;

    @Autowired
    private IAccountFlowService accountFlowService;

    @Autowired
    private IUserBankinfoService userBankinfoService;

    @Autowired
    private ISystemAccountService systemAccountService;

    @Override
    public PageResult query(MoneyWithdrawQueryObject qo) {
        int count = this.moneyWithdrawMapper.queryForCount(qo);
        if (count > 0) {
            List<MoneyWithdraw> list = this.moneyWithdrawMapper.query(qo);
            return new PageResult(list, count, qo.getCurrentPage(),
                    qo.getPageSize());
        }
        return PageResult.empty(qo.getPageSize());
    }

    /**
     * 提现审核
     * 1,查询前台用户的提现对象,进行必要的判断楼下的
     * 2,设置共同的参数
     * 3,判断审核通过还是不通过
     * 4,通过
     * 提现人的冻结金额没了,可用余额增加一部分,另一部分到系统的账户里面(管理费)
     * 提现人流水记录:
     * 提现
     * 手续费
     * 系统账户
     * 手续费增加
     * <p>
     * 5,不通过
     * 提现人的冻结金额没了,增加到可用余额里面
     * 增加对应的流水记录AccountFlow
     * 6,保存提现的账号
     * 7,更改用户的状态码
     */
    @Override
    public void audit(Long id, String remark, int state) {
        MoneyWithdraw moneyWithdraw = moneyWithdrawMapper.selectByPrimaryKey(id);
        //提现人帐号
        Account account = accountService.findById(moneyWithdraw.getApplier().getId());
        if (moneyWithdraw != null && moneyWithdraw.getState() == MoneyWithdraw.STATE_NORMAL) {
            moneyWithdraw.setRemark(remark);
            moneyWithdraw.setState(state);
            moneyWithdraw.setAuditor(UserContext.getLogininfo());
            moneyWithdraw.setAuditTime(new Date());
            if (state == MoneyWithdraw.STATE_AUDIT) {
                //冻结金额先扣除手续费
                account.setFreezedAmount(account.getFreezedAmount().subtract(moneyWithdraw.getCharge()));
                accountFlowService.withdrawSuccessFee(account, moneyWithdraw.getCharge());
                //系统账户增加的金额
                systemAccountService.withdrawFee(moneyWithdraw, account);
                //冻结金额再扣除真正提现费
                BigDecimal realWithdrawFee = moneyWithdraw.getAmount().subtract(moneyWithdraw.getCharge());
                account.setFreezedAmount(account.getFreezedAmount().subtract(realWithdrawFee));
                accountFlowService.withdrawSuccessReal(account, realWithdrawFee);




            } else {
                account.setFreezedAmount(account.getFreezedAmount().subtract(moneyWithdraw.getAmount()));
                account.setUsableAmount(account.getUsableAmount().add(moneyWithdraw.getAmount()));
                accountFlowService.withdrawFail(account, moneyWithdraw);
            }
            accountService.update(account);
            moneyWithdrawMapper.updateByPrimaryKey(moneyWithdraw);
            Userinfo userinfo = userinfoService.findById(moneyWithdraw.getApplier().getId());
            userinfo.removeState(BitStatesUtils.OP_HAS_MONEYWITHDRAW_PROCESS);
            userinfoService.update(userinfo);
        }

    }

    @Override
    public void apply(BigDecimal moneyAmount) {
        // 判断当前用户是否有一个提现申请,已经绑定银行卡
        // 判断提现金额<=用户可用余额 && 提现金额>=系统最小提现金额
        Userinfo current = userinfoService.getCurrent();
        Account account = accountService.getCurrent();
        if (current.getIsBindBank() && !current.getHasWithdrawProcess()
                && moneyAmount.compareTo(account.getUsableAmount()) <= 0
                && moneyAmount.compareTo(BidConst.MIN_WITHDRAW_AMOUNT) >= 0) {
            // 得到用户绑定的银行卡信息
            UserBankinfo ub = userBankinfoService.getByUser(current.getId());

            // 创建一个提现申请对象,设置相关属性;
            MoneyWithdraw m = new MoneyWithdraw();
            m.setAccountName(ub.getAccountName());
            m.setAccountNumber(ub.getAccountNumber());
            m.setAmount(moneyAmount);
            m.setApplier(UserContext.getLogininfo());
            m.setApplyTime(new Date());
            m.setBankForkName(ub.getBankForkName());
            m.setBankName(ub.getBankName());
            m.setCharge(BidConst.MONEY_WITHDRAW_CHARGEFEE);//也可以去计算出来
            m.setState(MoneyWithdraw.STATE_NORMAL);

            moneyWithdrawMapper.insert(m);
            // 对于账户:冻结金额,增加提现申请冻结流水;
            account.setUsableAmount(account.getUsableAmount().subtract(moneyAmount));
            account.setFreezedAmount(account.getFreezedAmount().add(moneyAmount));
            accountFlowService.moneyWithDrawApply(m, account);
            accountService.update(account);

            // 用户添加状态码
            current.addStatue(BitStatesUtils.OP_HAS_MONEYWITHDRAW_PROCESS);
            userinfoService.update(current);
        }
    }


//	@Override
//	public void audit(Long id, String remark, int state) {
//		// 得到提现申请单
//		MoneyWithdraw m = this.moneyWithdrawMapper.selectByPrimaryKey(id);
//		// 1,判断:提现单状态
//		if (m != null && m.getState() == MoneyWithdraw.STATE_NORMAL) {
//			// 2,设置相关参数
//			m.setAuditor(UserContext.getCurrent());
//			m.setAuditTime(new Date());
//			m.setRemark(remark);
//			m.setState(state);
//
//			Account account = this.accountService.get(m.getApplier().getId());
//			if (state == MoneyWithdraw.STATE_AUDIT) {
//				// 3,如果审核通过
//				// 1,冻结金额减少(减少手续费),增加提现支付手续费流水;
//				account.setFreezedAmount(account.getFreezedAmount().subtract(
//						m.getCharge()));
//				this.accountFlowService.withDrawChargeFee(m, account);
//				// 2,系统账户增加可用余额,增加收取提现手续费流水;
//				this.systemAccountService.chargeWithdrawFee(m);
//
//				// 3,冻结金额减少(减少提现金额);增加提现成功流水;
//				BigDecimal realWithdrawFee = m.getAmount().subtract(
//						m.getCharge());
//				account.setFreezedAmount(account.getFreezedAmount().subtract(
//						realWithdrawFee));
//				this.accountFlowService.withDrawSuccess(realWithdrawFee,
//						account);
//
//			} else {
//				// 4,如果审核拒绝
//				// 1,取消冻结金额,可用余额增加,增加去掉冻结流水
//				account.setFreezedAmount(account.getFreezedAmount().subtract(
//						m.getAmount()));
//				account.setUsableAmount(account.getUsableAmount().add(
//						m.getAmount()));
//				this.accountFlowService.withDrawFailed(m, account);
//			}
//			this.accountService.update(account);
//			this.moneyWithdrawMapper.updateByPrimaryKey(m);
//			// 5,取消用户状态码
//			Userinfo userinfo = this.userinfoService
//					.get(m.getApplier().getId());
//			userinfo.removeState(BitStatesUtils.OP_HAS_MONEYWITHDRAW_PROCESS);
//			this.userinfoService.update(userinfo);
//		}
//	}

}
